<template>
  <div class="tree-wrapper">
    <div class="tree-container">
      <div class="header">
        <el-tooltip :content="useCompanyStore().currentCompany.name" placement="top" :show-after="500">
          <span class="company-name">
            {{ useCompanyStore().currentCompany.name }}
          </span>
        </el-tooltip>

        <div class="header-actions" v-if="isDeviceInfoRoute && isEdit">
          <a @click="addRootMeter">
            <el-tooltip content="新增一级表计" placement="top" :show-after="500">
              <i class="fa fa-plus"></i>
            </el-tooltip>
          </a>
          <a @click="refresh">
            <el-tooltip content="刷新表计列表" placement="top" :show-after="500">
              <i class="fa fa-refresh"></i>
            </el-tooltip>
          </a>
          <a v-if="!isAllChecked" @click="checkAllNodes" title="全选">
            <i class="fa fa-square-o"></i>
          </a>
          <a v-else @click="uncheckAllNodes" title="取消全选">
            <i class="fa fa-check-square-o"></i>
          </a>
          <el-dropdown @command="handleMoreActions" trigger="click">
            <a style="display: flex; align-items: center; justify-content: center;">
              <el-tooltip content="更多操作" placement="top" :show-after="500">
                <i class="fa fa-ellipsis-h"></i>
              </el-tooltip>
            </a>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="batchDelete">批量删除</el-dropdown-item>
                <el-dropdown-item command="batchSetParent">批量设置父节点</el-dropdown-item>
                <el-dropdown-item command="batchSetEngine">批量设置引擎</el-dropdown-item>
                <el-dropdown-item command="batchSetInfo">批量设置表计信息</el-dropdown-item>
                <el-dropdown-item command="batchSetUploadTime">批量设置上传时间</el-dropdown-item>
                <!-- 下划线  -->
                <el-dropdown-item v-if="hasWaterMeters" command="createRingNetwork">组成环网</el-dropdown-item>
                <el-dropdown-item v-if="hasWaterMeters" command="createWaterNetwork">组成水网</el-dropdown-item>
                <el-dropdown-item command="batchImport">批量导入</el-dropdown-item>
                <el-dropdown-item command="exportSelected">导出选中表计</el-dropdown-item>
                <el-dropdown-item command="exportAll">导出所有表计</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <el-tree :check-strictly="true" @node-click="handleClick" style="display: inline-block; width: 100%"
        v-loading="loading" element-loading-text="loading..." :show-checkbox="isDeviceInfoRoute && isEdit" ref="treeRef"
        :indent="10" class="eye-tree" :data="data" :props="defaultProps" node-key="id" :highlight-current="true"
        :default-expand-all="true" :expand-on-click-node="false">
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <el-tooltip :content="node.label" placement="top" :show-after="500">
              <span class="node-label">{{ node.label }}</span>
            </el-tooltip>
            <span class="node-actions" v-if="isDeviceInfoRoute && isEdit">
              <a @click="append(data)">
                <i class="fa fa-plus"></i>
              </a>
              <el-popconfirm placement="top" :title="`确定删除${node.label}表计吗？`" @confirm="remove(node, data)">
                <template #reference>
                  <a>
                    <i class="fa fa-minus"></i>
                  </a>
                </template>
              </el-popconfirm>
            </span>
          </div>
        </template>
      </el-tree>

      <!-- 批量导入组件 -->
      <BatchImportMeter v-model:visible="batchImportDialogVisible" @success="handleImportSuccess" />

      <!-- 现有对话框保持不变 -->
      <el-dialog draggable :title="currentMeter ? '编辑表计' : '新增表计'" destroy-on-close align-center
        v-model="dialogVisible">
        <MeterDialog @update:visible="dialogVisible = false" :pMeter="parent_meter"
          :id="currentMeter ? +currentMeter.meter_id : null" />
      </el-dialog>

      <el-dialog v-model="deviceTypeDialogVisible" title="选择设备类型" width="500px">
        <div class="device-type-container">
          <div class="device-type-item" @click="handleDeviceTypeSelect(1)">
            <i class="fa fa-tint"></i>
            <span>水表</span>
          </div>
          <div class="device-type-item" @click="handleDeviceTypeSelect(2)">
            <i class="fa fa-bolt"></i>
            <span>电表</span>
          </div>
          <div class="device-type-item" @click="handleDeviceTypeSelect(3)">
            <i class="fa fa-fire"></i>
            <span>气表</span>
          </div>
          <div class="device-type-item" @click="handleDeviceTypeSelect(6)">
            <i class="fa fa-tachometer"></i>
            <span>压力表</span>
          </div>
        </div>
      </el-dialog>

      <el-dialog destroy-on-close append-to-body draggable v-model="setParentDialogVisible" title="选择要设置的父节点"
        width="700px">
        <div class="set-parent-container">
          <div class="selected-meters">
            <div class="selected-meters-header">
              <h4>已选择的表计</h4>
              <span class="meter-count">共 {{ selectedNodes.length }} 个</span>
            </div>
            <div class="selected-meters-list">
              <el-tag v-for="node in selectedNodes" :key="node.id" class="meter-tag" size="small">
                {{ node.label }}
              </el-tag>
            </div>
          </div>
          <div class="divider"></div>
          <div class="tree-section">
            <h4>选择新的父节点</h4>
            <el-select filterable placeholder="请选择父节点" v-model="selectedParent">
              <el-option v-for="node in meterStore.meterList" :key="node.id" :label="node.meter_code"
                :value="node.id"></el-option>
            </el-select>
          </div>
          <div class="dialog-footer">
            <el-button @click="setParentDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmSetParent">确认</el-button>
          </div>
        </div>
      </el-dialog>

      <el-dialog destroy-on-close append-to-body draggable v-model="setEngineDialogVisible" title="选择要设置的引擎"
        width="700px">
        <div class="set-engine-container">
          <div class="selected-meters">
            <div class="selected-meters-header">
              <h4>已选择的表计</h4>
              <span class="meter-count">共 {{ selectedNodes.length }} 个</span>
            </div>
            <div class="selected-meters-list">
              <el-tag v-for="node in selectedNodes" :key="node.id" class="meter-tag" size="small">
                {{ node.label }}
              </el-tag>
            </div>
          </div>
          <div class="divider"></div>
          <div class="tree-section">
            <h4>选择新的引擎</h4>
            <el-select filterable placeholder="请选择引擎" v-model="selectedEngine">
              <el-option v-for="engine in engineList" :key="engine.value" :label="engine.label"
                :value="engine.value"></el-option>
            </el-select>
          </div>
          <div class="dialog-footer">
            <el-button @click="setEngineDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmSetEngine">确认</el-button>
          </div>
        </div>
      </el-dialog>

      <el-dialog destroy-on-close append-to-body draggable v-model="batchSetInfoDialogVisible" title="批量设置表计信息"
        width="800px">
        <div class="batch-set-info-container">
          <div class="selected-meters">
            <div class="selected-meters-header">
              <h4>已选择的表计</h4>
              <span class="meter-count">共 {{ selectedNodes.length }} 个</span>
            </div>
            <div class="selected-meters-list">
              <el-tag v-for="node in selectedNodes" :key="node.id" class="meter-tag" size="small">
                {{ node.label }}
              </el-tag>
            </div>
          </div>
          <div class="divider"></div>
          <el-form :model="batchSetForm" label-width="120px" class="batch-form">
            <div class="form-section">
              <h4>基础信息</h4>
              <div class="form-item-split">
                <el-form-item label="区域">
                  <el-select filterable v-model="batchSetForm.area_id" clearable placeholder="请选择区域"
                    style="width: 100%;">
                    <el-option v-for="area in avaliableAreaList" :key="area.id" :label="area.name"
                      :value="area.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="用途">
                  <el-select v-model="batchSetForm.sub_category" filterable allow-create clearable
                    placeholder="请选择或创建用途" style="width: 100%;">
                    <el-option-group v-for="(options, group) in groupedCategoryOptions" :key="group" :label="group">
                      <el-option v-for="option in options" :key="option" :label="option" :value="option" />
                    </el-option-group>
                  </el-select>
                </el-form-item>
              </div>
              <div class="form-item-split">
                <el-form-item label="父节点">
                  <el-select filterable v-model="batchSetForm.parent_id" clearable placeholder="请选择父节点"
                    style="width: 100%;">
                    <el-option v-for="node in meterStore.meterList" :key="node.id" :label="node.meter_code"
                      :value="node.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="引擎">
                  <el-select filterable v-model="batchSetForm.engine_id" clearable placeholder="请选择引擎"
                    style="width: 100%;">
                    <el-option v-for="engine in engineList" :key="engine.value" :label="engine.label"
                      :value="engine.value"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>

            <div class="form-section">
              <h4>安装信息</h4>
              <div class="form-item-split">
                <el-form-item label="楼栋">
                  <el-select v-model="batchSetForm.cell" placeholder="请选择楼栋" filterable allow-create
                    style="width: 100%;">
                    <el-option v-for="cell in cellOptions" :key="cell" :label="cell" :value="cell" />
                  </el-select>
                </el-form-item>
                <el-form-item label="供应点位">
                  <el-input v-model="batchSetForm.supply_region" placeholder="请输入供应点位" style="width: 100%;" />
                </el-form-item>
              </div>
              <div class="form-item-split">
                <el-form-item label="安装位置">
                  <el-input v-model="batchSetForm.installation_location" placeholder="请输入安装位置" style="width: 100%;" />
                </el-form-item>
                <el-form-item label="规格">
                  <el-select v-model="batchSetForm.specification" placeholder="请选择表计规格" filterable allow-create
                    style="width: 100%;">
                    <el-option v-for="spec in specificationOptions" :key="spec" :label="spec" :value="spec" />
                  </el-select>
                </el-form-item>
              </div>
            </div>

            <div class="form-section">
              <h4>计量信息</h4>
              <div class="form-item-split">
                <el-form-item label="折标煤系数">
                  <el-select v-model="batchSetForm.standard_coal_factor" placeholder="请选择折标煤系数" filterable allow-create
                    style="width: 100%;">
                    <el-option v-for="factor in STANDARD_COAL_FACTORS" :key="factor.value"
                      :label="`${factor.label} (${factor.value})`" :value="factor.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="制造商">
                  <el-input v-model="batchSetForm.manufacturer" placeholder="请输入制造商" style="width: 100%;" />
                </el-form-item>
              </div>
              <div class="form-item-split">
                <el-form-item label="参与在线统计">
                  <el-switch v-model="batchSetForm.check_no_record" inline-prompt active-text="是" inactive-text="否" />
                </el-form-item>
                <el-form-item label="参与离线统计">
                  <el-switch v-model="batchSetForm.is_drain_considerd" inline-prompt active-text="是"
                    inactive-text="否" />
                </el-form-item>
              </div>
            </div>
          </el-form>
          <div class="dialog-footer">
            <el-button @click="batchSetInfoDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmBatchSetInfo">确认</el-button>
          </div>
        </div>
      </el-dialog>

      <!-- 新增：批量设置上传时间对话框 -->
      <el-dialog destroy-on-close append-to-body draggable v-model="batchSetUploadTimeDialogVisible" title="批量设置上传时间"
        width="700px">
        <div class="batch-set-upload-time-container">
          <!-- 协议提示信息 -->
          <el-alert title="温馨提示" type="info" :closable="false" show-icon style="margin-bottom: 20px;">
            <template #default>
              <div>
                <p>1. 由于协议是被动型，设置会在下一次表上线推送时才能发送过去</p>
                <p>2. 仅适用于引擎ID为18的表计</p>
                <p>3. 未绑定设备的表计会自动创建并绑定设备</p>
              </div>
            </template>
          </el-alert>

          <div class="selected-meters">
            <div class="selected-meters-header">
              <h4>已选择的表计</h4>
              <span class="meter-count">共 {{ validUploadTimeMeters.length }} 个符合条件 / {{ selectedNodes.length }}
                个已选</span>
            </div>
            <div class="selected-meters-list">
              <el-tag v-for="node in selectedNodes" :key="node.id" class="meter-tag" size="small"
                :type="node.engine_id === 18 ? '' : 'info'">
                {{ node.label }} {{ node.engine_id !== 18 ? '(不支持)' : '' }}
              </el-tag>
            </div>
          </div>

          <div class="divider"></div>

          <el-form label-width="100px">
            <el-form-item label="上传时间">
              <div style="display: flex; gap: 10px; align-items: center;">
                <el-input-number v-model="batchUploadTime.hour" :min="0" :max="23" :step="1" />
                <span>时</span>
                <el-input-number v-model="batchUploadTime.minute" :min="0" :max="59" :step="1" />
                <span>分</span>
              </div>
            </el-form-item>
          </el-form>

          <div class="dialog-footer">
            <el-button @click="batchSetUploadTimeDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmBatchSetUploadTime" :loading="batchUploadTimeLoading"
              :disabled="validUploadTimeMeters.length === 0">
              确认设置 ({{ validUploadTimeMeters.length }})
            </el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { deleteMeterApi, addMeterApi, updateMeterApi } from "@/api/meter";
import { addDeviceApi, getDeviceListApi, runDeviceCommandApi } from "@/api/device";
import { useCompanyStore } from "@/stores/company";
import { useMeterStore } from "@/stores/meter";
import { ref, computed, onMounted, reactive } from "vue";
import { useRoute } from "vue-router";
import { handleError } from "@/utils/handleError";
import { usePermissionStore } from "@/stores/permission";
import { engineList, STANDARD_COAL_FACTORS, categoryMap } from "@/constants";
import { useAreaStore } from "@/stores/area";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import BatchImportMeter from "./components/BatchImportMeter.vue";
import { useExportMeters } from "./hooks/useExportMeters";

let permisstionStore = usePermissionStore()

const isEdit = permisstionStore.hasPermission('manage_device')

const { exportSelectedMeters, exportAllMeters } = useExportMeters();

const route = useRoute();
const isDeviceInfoRoute = computed(() => route.name === "DeviceInfo");
const hasWaterMeters = computed(() => {
  return meterStore.meterList.some(meter => meter.type === 1)
})
const compnayStore = useCompanyStore();
const areaStore = useAreaStore();

const avaliableAreaList = computed(() => {
  return [
    { id: -1, name: "无" },
    ...areaStore.areas.map(item => {
      return { id: item.id, name: item.name };
    })
  ]
});

const cellOptions = computed(() => {
  const cells = meterStore.meterList.map(meter => meter.cell).filter(cell => cell);
  return [...new Set(cells)];
});

const specificationOptions = computed(() => {
  const specs = meterStore.meterList.map(meter => meter.specification).filter(spec => spec);
  return [...new Set(specs)];
});

const getAllPresetCategories = () => {
  const allCategories = [];
  for (const group in categoryMap) {
    for (const category of categoryMap[group]) {
      allCategories.push(category);
    }
  }
  return allCategories;
};

const categoryOptions = ref([]);
const groupedCategoryOptions = computed(() => {
  const result = {};
  result['基础'] = ['无'];
  const allPresetCategories = getAllPresetCategories();
  const customCategories = [...new Set(
    categoryOptions.value.filter(category => !allPresetCategories.includes(category) && category !== '无')
  )];
  if (customCategories.length > 0) {
    result['自定义'] = customCategories;
  }
  for (const group in categoryMap) {
    if (group !== '自定义') {
      result[group] = [...categoryMap[group]];
    }
  }
  return result;
});

const fetchAllCategories = async () => {
  try {
    const existingCategories = meterStore.meterList
      .map((meter) => meter.sub_category)
      .filter((category) => category && category.trim() !== "");
    categoryOptions.value = [...new Set(existingCategories)];
  } catch (error) {
    handleError(error, "获取用途数据失败", true);
  }
};

const batchImportDialogVisible = ref(false);

onMounted(async () => {
  if (!areaStore.areas.length) {
    await areaStore.fetchAreas();
  }
  await fetchAllCategories();
});

let props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
});
const loading = ref(false);
const dialogVisible = ref(false);
const deviceTypeDialogVisible = ref(false);
const setParentDialogVisible = ref(false);
const setEngineDialogVisible = ref(false);
const selectedEngine = ref(null);
const currentMeter = ref(null);
const parent_meter = ref(null);
const selectedNodes = ref([]);
const treeRef = ref(null);
const selectedParent = ref(null);
const defaultProps = {
  id: "id",
  children: "children",
  label: "label",
};
let meterStore = useMeterStore();

const batchSetInfoDialogVisible = ref(false);
const batchSetForm = ref({
  area_id: null,
  sub_category: "",
  parent_id: null,
  engine_id: null,
  cell: "",
  supply_region: "",
  installation_location: "",
  specification: "",
  standard_coal_factor: null,
  manufacturer: "",
  check_no_record: true,
  is_drain_considerd: true
});

// 新增：批量设置上传时间相关状态
const batchSetUploadTimeDialogVisible = ref(false);
const batchUploadTimeLoading = ref(false);
const batchUploadTime = reactive({
  hour: 23,
  minute: 0
});

// 筛选出支持设置上传时间的表计（engine_id === 18）
const validUploadTimeMeters = computed(() => {
  return selectedNodes.value.filter(node => node.engine_id === 18);
});

const emit = defineEmits(["refresh", "select"]);

const handleImportSuccess = async (result) => {
  const { successCount, failCount, totalCount } = result;
  ElMessage.success(`导入完成！成功: ${successCount}, 失败: ${failCount}`);
  await refresh();
};

function append(data) {
  parent_meter.value = data;
  currentMeter.value = null;
  dialogVisible.value = true;
}

function addRootMeter() {
  parent_meter.value = {
    id: null,
    label: "根节点",
    type: null,
  };
  currentMeter.value = null;
  deviceTypeDialogVisible.value = true;
}

async function handleDeviceTypeSelect(type) {
  meterStore.setCurrentSelectedType(type);
  try {
    await meterStore.fetchMeterList({
      type: type,
    })
  } catch (error) {
    handleError(error, "获取父级表计列表失败");
  }
  deviceTypeDialogVisible.value = false;
  dialogVisible.value = true;
}

function handleClick(node) {
  if (node) {
    meterStore.setCurrentMeter(node);
    emit("select", node);
  }
}

function remove(node, data) {
  if (data && data.id) {
    let arr = [data.id];
    deletePost(arr);
  }
}

const removeMeters = () => {
  const checkedNodes = treeRef.value?.getCheckedNodes(false, false) || [];
  const nodeIds = checkedNodes.map((node) => node.id).filter(Boolean);
  if (nodeIds.length > 0) {
    deletePost(nodeIds);
  }
};

function deletePost(arr) {
  if (!Array.isArray(arr) || arr.length === 0) return;

  deleteMeterApi(arr)
    .then((res) => {
      ElMessage.success("删除成功");
      refresh();
    })
    .catch((err) => {
      handleError(err, "删除失败");
    });
}

function handleMoreActions(command) {
  let nodes;
  switch (command) {
    case 'batchDelete':
      nodes = treeRef.value?.getCheckedNodes(false, false) || [];
      if (nodes.length === 0) {
        ElMessage.warning('请先选择要删除的表计');
        return;
      }
      ElMessageBox.confirm('确定批量删除选中的表计吗？')
        .then(() => {
          removeMeters();
        })
        .catch(() => { });
      break;
    case 'batchSetParent':
      nodes = treeRef.value?.getCheckedNodes(false, false) || [];
      if (nodes.length === 0) {
        ElMessage.warning('请先选择要设置的表计');
        return;
      }
      selectedNodes.value = nodes;
      setParentDialogVisible.value = true;
      break;
    case 'batchSetEngine':
      nodes = treeRef.value?.getCheckedNodes(false, false) || [];
      if (nodes.length === 0) {
        ElMessage.warning('请先选择要设置的表计');
        return;
      }
      selectedNodes.value = nodes;
      setEngineDialogVisible.value = true;
      break;
    case 'batchSetInfo':
      nodes = treeRef.value?.getCheckedNodes(false, false) || [];
      if (nodes.length === 0) {
        ElMessage.warning('请先选择要设置的表计');
        return;
      }
      selectedNodes.value = nodes;
      batchSetInfoDialogVisible.value = true;
      break;
    case 'batchSetUploadTime':
      nodes = treeRef.value?.getCheckedNodes(false, false) || [];
      if (nodes.length === 0) {
        ElMessage.warning('请先选择要设置的表计');
        return;
      }
      selectedNodes.value = nodes;
      // 检查是否有支持的表计
      const validMeters = nodes.filter(node => node.engine_id === 18);
      if (validMeters.length === 0) {
        ElMessage.warning('选中的表计中没有支持设置上传时间的表计（需要引擎为山东沂润表计）');
        return;
      }
      batchSetUploadTimeDialogVisible.value = true;
      break;
    case 'batchImport':
      batchImportDialogVisible.value = true;
      break;
    case 'exportSelected':
      nodes = treeRef.value?.getCheckedNodes(false, false) || [];
      if (nodes.length === 0) {
        ElMessage.warning('请先选择要导出的表计');
        return;
      }
      exportSelectedMeters(nodes, meterStore.meterList);
      break;
    case 'exportAll':
      exportAllMeters(meterStore.meterList);
      break;
    case 'createRingNetwork':
      nodes = treeRef.value?.getCheckedNodes(false, false) || [];
      if (nodes.length < 2) {
        ElMessage.warning('请至少选择两个水表组成环网');
        return;
      }
      ElMessageBox.confirm('确定将所选水表组成环网？')
        .then(() => {
          addRingNetwork(nodes);
        })
        .catch(() => { });
      break;
  }
}

async function addRingNetwork(nodes) {
  let meter_code = nodes.map(node => node.meter_code).join(',');
  let meter_id = nodes.map(node => node.id).join(',');
  loading.value = true;
  try {
    await addMeterApi({
      company_id: compnayStore.currentCompany.id,
      meter_code: '环网' + "(" + meter_code + ")",
      meter_id: meter_id,
      installation_date: dayjs().toISOString(),
      type: 1,
      status: 1,
      meter_name: '环网',
      engine_id: 10,
      is_unknown_water_considered: false,
      is_drain_considerd: false,
      check_no_record: false,
    })
    ElMessage.success("组成环网成功");
    await refresh();
  } catch (error) {
    handleError(error, "组成环网失败");
  } finally {
    loading.value = false;
  }
}

async function confirmSetParent() {
  let parent_id = selectedParent.value;
  if (!parent_id) {
    ElMessage.warning('请先选择父节点');
    return;
  }
  try {
    loading.value = true;
    for (const node of selectedNodes.value) {
      await updateMeterApi({
        id: node.id,
        parent_id: parent_id,
      });
    }
    setParentDialogVisible.value = false;
    await refresh();
    ElMessage.success('批量设置父节点成功');
  } catch (error) {
    handleError(error, "设置父节点失败");
  } finally {
    loading.value = false;
  }
}

const confirmSetEngine = async () => {
  let engine_id = selectedEngine.value;
  if (!engine_id) {
    ElMessage.warning('请先选择引擎');
    return;
  }
  try {
    loading.value = true;
    for (const node of selectedNodes.value) {
      await updateMeterApi({
        id: node.id,
        engine_id: engine_id,
      });
    }
    setEngineDialogVisible.value = false;
    await refresh();
    ElMessage.success('批量设置引擎成功');
  } catch (error) {
    handleError(error, "设置引擎失败");
  } finally {
    loading.value = false;
  }
}

async function confirmBatchSetInfo() {
  try {
    loading.value = true;
    const updateData = {};
    Object.keys(batchSetForm.value).forEach(key => {
      if (batchSetForm.value[key] !== null && batchSetForm.value[key] !== '') {
        updateData[key] = batchSetForm.value[key];
      }
    });

    for (const node of selectedNodes.value) {
      await updateMeterApi({
        id: node.id,
        ...updateData
      });
    }
    batchSetInfoDialogVisible.value = false;
    await refresh();
    ElMessage.success('批量设置表计信息成功');
  } catch (error) {
    handleError(error, "设置表计信息失败");
  } finally {
    loading.value = false;
  }
}

// 新增：批量设置上传时间的确认函数
async function confirmBatchSetUploadTime() {
  if (validUploadTimeMeters.value.length === 0) {
    ElMessage.warning('没有符合条件的表计可以设置');
    return;
  }

  try {
    batchUploadTimeLoading.value = true;

    let successCount = 0;
    let failCount = 0;
    const errors = [];

    for (const meter of validUploadTimeMeters.value) {
      try {
        await setMeterUploadTime(meter, batchUploadTime.hour, batchUploadTime.minute);
        successCount++;
      } catch (error) {
        failCount++;
        errors.push({
          meter: meter.label,
          error: error.message
        });
      }
    }

    batchSetUploadTimeDialogVisible.value = false;

    if (failCount === 0) {
      ElMessage.success(`批量设置上传时间成功！共设置 ${successCount} 个表计`);
    } else {
      ElMessage.warning(`设置完成！成功: ${successCount}, 失败: ${failCount}`);
      console.error('设置失败的表计:', errors);
    }

    await refresh();
  } catch (error) {
    handleError(error, "批量设置上传时间失败");
  } finally {
    batchUploadTimeLoading.value = false;
  }
}

/**
 * 设置单个表计的上传时间
 */
async function setMeterUploadTime(meter, hour, minute) {
  let device;

  if (!meter.device_id) {
    // 查找或创建设备
    const deviceList = await getDeviceListApi({
      type: 1,
      offset: 0,
      limit: 500,
      company_id: compnayStore.currentCompany.id,
    });

    device = deviceList.data.find((item) => item.name === meter.meter_code);

    if (!device) {
      // 创建新设备
      await addDeviceApi({
        name: meter.meter_code,
        type: 1,
        engine_id: 18,
        company_id: compnayStore.currentCompany.id
      });

      // 重新获取设备
      const newDeviceList = await getDeviceListApi({
        type: 1,
        offset: 0,
        limit: 500,
        company_id: compnayStore.currentCompany.id,
      });
      device = newDeviceList.data.find((item) => item.name === meter.meter_code);

      if (!device) {
        throw new Error('创建设备失败');
      }
    }

    // 绑定设备到表计
    await updateMeterApi({
      id: meter.id,
      device_id: device.id
    });
  } else {
    // 已有设备ID，直接获取设备信息
    const deviceList = await getDeviceListApi({
      type: 1,
      offset: 0,
      limit: 500,
      company_id: compnayStore.currentCompany.id,
    });
    device = deviceList.data.find((item) => item.name === meter.meter_code);

    if (!device) {
      throw new Error('未找到对应设备');
    }
  }

  // 执行设置上传时间命令
  await runDeviceCommandApi({
    id: device.id,
    command_id: 1,
    raw: {
      hour: hour,
      minute: minute,
    }
  });
}

const refresh = async () => {
  loading.value = true;
  try {
    emit("refresh");
  } catch (error) {
    handleError(error, "刷新失败", true);
  } finally {
    loading.value = false;
  }
};

function checkAllNodes() {
  const allIds = meterStore.meterList.map(item => item.id);
  treeRef.value.setCheckedKeys(allIds);
}

function uncheckAllNodes() {
  treeRef.value.setCheckedKeys([]);
}

const isAllChecked = computed(() => {
  const allIds = meterStore.meterList.map(item => item.id);
  const checkedKeys = treeRef.value?.getCheckedKeys(false) || [];
  return allIds.length > 0 && checkedKeys.length === allIds.length;
});
</script>

<style scoped>
.tree-wrapper {
  width: 100%;
  height: 100%;
  overflow: auto;
}

.tree-container {
  height: 100%;
  background-color: #fff;
  min-width: 200px;
}

.header {
  padding: 0.3rem 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #333;
  margin-bottom: 1rem;
}

.company-name {
  max-width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
}

.set-parent-container,
.set-engine-container,
.batch-set-upload-time-container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.selected-meters {
  padding: 1rem;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.selected-meters-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.selected-meters-header h4 {
  margin: 0;
  color: #606266;
}

.meter-count {
  color: #909399;
  font-size: 0.9rem;
}

.selected-meters-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.meter-tag {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.divider {
  height: 1px;
  background-color: #dcdfe6;
  margin: 0.5rem 0;
}

.tree-section {
  h4 {
    margin: 0 0 0.5rem 0;
    color: #606266;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #dcdfe6;
}

.header-actions {
  display: flex;
  gap: 0.5rem;
}

a {
  padding: 0.1rem 0.4rem;
  border-radius: 0.2rem;
  color: #333;
  cursor: pointer;
  transition: all 0.2s;
}

a:hover {
  background-color: #e6e6e6;
  color: #333;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 0.8rem;
  padding-right: 0.5rem;
  width: 100%;
}

.node-label {
  max-width: 80%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 50px;
}

.node-actions {
  visibility: hidden;
  display: flex;
  gap: 0.3rem;
}

.custom-tree-node:hover .node-actions {
  visibility: visible;
}

.fa {
  font-size: 0.8rem;
}

.ring-network-container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.ring-settings {
  margin-top: 1rem;
}

.device-type-container {
  display: flex;
  justify-content: space-around;
  padding: 20px;
  gap: 15px;
}

.device-type-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.device-type-item:hover {
  color: #409eff;
  border-color: #409eff;
  background-color: #ecf5ff;
}

.device-type-item i {
  font-size: 24px;
  margin-bottom: 10px;
  color: #409eff;
}

.device-type-item span {
  font-size: 14px;
  color: #606266;
}

.device-type-item:hover span {
  color: #409eff;
}

.batch-set-info-container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.form-section {
  background-color: #f5f7fa;
  padding: 1rem;
  border-radius: 4px;
}

.form-section h4 {
  margin: 0 0 1rem 0;
  color: #606266;
  font-size: 14px;
}

.batch-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.form-item-split {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
}

.form-item-split .el-form-item {
  flex: 1;
  margin-bottom: 0;
}
</style>